import { defineStore } from 'pinia';
import { AsyncData } from '#app';
import { Menu, MenuType } from '~~/types/menu.d';
import { RouteLocation } from 'vue-router';
import { Status } from '~~/types/status.d';
// export interface MenuItem {
//   title: string;
//   path: string;
//   icon?: string;
//   children?: MenuItem[];
//   [propName: string]: any;
// }
// <AsyncData<any[],>>
export interface MenuMapItem {
  menu: Menu;
  route: RouteLocation | null;
  children: MenuMapItem[];
}

export type MenuMap<T = string> = Map<T, MenuMapItem>;

export default defineStore('menus', () => {
  const auth = useAuth();

  const menu = useFetchApi('/system/menu', {
    query: {
      status: Status.enable,
    },
    default: (): Menu[] => [],
    watch: [auth.accessToken],
  });
  watchAsyncDataError(menu);

  const menuMap = computed(() => {
    // const tree = new Set();

    const map: MenuMap =
      menu.data.value?.reduce((map, value) => {
        map.set(value.key, {
          menu: value,
          route:
            value.type === MenuType.page && value.path
              ? useRouter().resolve(value.path)
              : null,
          children: [],
        });
        return map;
      }, new Map()) || new Map();

    menu.data.value?.forEach((value) => {
      const item = map.get(value.key);
      if (!item) return;
      // if (!item.children) {
      //   item.children = [];
      // }
      // if (!item.childrenByRoleFilter) {
      //   item.childrenByRoleFilter = [];
      // }
      // if (!value.parent) {
      //   return;
      // }
      if (value.parent && map.has(value.parent)) {
        const parent = map.get(value.parent);
        if (!parent) return;
        // if (!parent.children) {
        //   parent.children = [];
        // }
        // if (!parent.childrenByRoleFilter) {
        //   parent.childrenByRoleFilter = [];
        // }
        parent.children.push(item);
        // if (auth.hasMenu(value.key)) {
        //   parent.childrenByRoleFilter.push(item);
        // }
      }
    });

    return map;
  });

  // console.log(
  //   '🚀 ~ file: useNavMenu.ts:31 ~ menuMapById ~ menuMapById:',
  //   menuMapById,
  // );

  // const menuMapByKey = computed(() => {
  //   return menu.data.value.reduce((map, value) => {
  //     map.set(value.key, menuMapById.value.get(value.id));
  //     return map;
  //   }, new Map());
  // });

  const routeMap = computed(() => {
    return [...menuMap.value.values()]
      .filter((value) => value.route)
      .reduce((map, value) => {
        map.set(<string>value.menu.path, value);
        return map;
      }, <MenuMap>new Map());
  });

  const menusTree = computed(() =>
    menu.data.value
      ?.filter((value) => !value.parent)
      .map((value) => menuMap.value.get(value.key)),
  );

  const route = useRoute();

  function getMenuByPath(path: string) {
    const route = useRouter().resolve(path);
    // console.log('🚀 ~ file: useMenus.ts:104 ~ getMenuByPath ~ route:', route);
    let currentRouteMenu;
    if (routeMap.value.has(path)) {
      currentRouteMenu = routeMap.value.get(route.path);
    } else if (
      routeMap.value.has(route.matched[route.matched.length - 1].path)
    ) {
      currentRouteMenu = routeMap.value.get(
        route.matched[route.matched.length - 1].path,
      );
    }

    return currentRouteMenu;
  }

  const currentRouteMenus = computed(() => {
    const list = [];
    // console.log(route.path);

    let currentRouteMenu = getMenuByPath(route.path);
    // console.log(
    //   '🚀 ~ file: useMenus.ts:119 ~ currentRouteMenus ~ currentRouteMenu:',
    //   currentRouteMenu,
    // );
    // if (routeMap.value.has(route.path)) {
    //   currentRouteMenu = routeMap.value.get(route.path);
    // } else if (routeMap.value.has(route.matched[0].path)) {
    //   currentRouteMenu = routeMap.value.get(route.matched[0].path);
    // }
    while (currentRouteMenu) {
      // console.log(
      //   '🚀 ~ file: useNavMenu.ts:91 ~ currentRouteMenus ~ currentRouteMenu:',
      //   currentRouteMenu,
      // );

      list.unshift(currentRouteMenu);
      if (currentRouteMenu.menu.parent) {
        currentRouteMenu = menuMap.value.get(currentRouteMenu.menu.parent);

        // console.log(
        //   '🚀 ~ file: useMenus.ts:119 ~ currentRouteMenus ~ currentRouteMenu:',
        //   currentRouteMenu,
        // );
      } else {
        currentRouteMenu = undefined;
      }
    }
    return list;
  });
  // const auth = useAuth();

  // const menusByRoleFilter = computed(() => {
  //   return menu.data.value?.filter((value) => auth.hasMenu(value.key));
  // });

  // const menuMapByRoleFilter = computed(() => {});

  return {
    data: menu.data,
    pending: menu.pending,
    error: menu.error,
    refresh: menu.refresh,
    execute: menu.execute,
    raw: menu,
    menuMap,
    routeMap,
    currentRouteMenus,
    menusTree,
    getMenuByPath,
    // menusByRoleFilter,
  };
});
